//
//  WriteRecipeViewController.m
//  ForengnMenu
//
//  Created by wenzhaoxu on 16/1/18.
//  Copyright © 2016年 余旺. All rights reserved.
//

#import "WriteRecipeViewController.h"
#import "menuNameTableViewCell.h"
#import "writeNameViewController.h"
#import "stepsTableViewCell.h"
#import "writeStepsViewController.h"
#import "WriteModel.h"
#import "MyMenuViewController.h"

@interface WriteRecipeViewController ()<UITableViewDataSource,UITableViewDelegate,stepsTableViewCellDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property NSString * identifier;

@property (weak, nonatomic) IBOutlet UITableView *myTableVIew;
//菜谱名
@property UILabel * writeName;
//心得
@property UILabel * tipsLabel;
//小贴士
@property UILabel * promptLabel;
//
@property UILabel * stepsLabel;

@property  NSMutableArray * array;//做菜步伐

@property UIImageView * iamegView;

@property NSIndexPath * selectedImageViewIndexPath;

@property NSString * message;

@property UIImageView * headImage;

@end

@implementation WriteRecipeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _writeName = [UILabel new];
    
    _tipsLabel = [UILabel new];
    
    _promptLabel = [UILabel new];
    
    _array = [NSMutableArray new];
    
    _iamegView = [UIImageView new];
    
    _headImage = [UIImageView new];
    
    //给默认一个步伐
    WriteModel * model = [WriteModel new];
    [_array addObject:model];
    
    _stepsLabel = [UILabel new];
    
    self.title = @"写菜谱";

    //设置右侧按钮标题方式
    UIButton * rightBnt = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBnt setTitle:@"存草稿" forState:UIControlStateNormal];
    [rightBnt setTitleColor:[UIColor colorWithRed:248/255.0f green:102/255.0f blue:79/255.0f alpha:1.0f] forState:UIControlStateNormal];
    
    rightBnt.titleLabel.font = [UIFont systemFontOfSize:16];
    
    rightBnt.frame = CGRectMake(0, 0, 48, 30);
    
    [rightBnt addTarget:self action:@selector(saveDraft) forControlEvents:UIControlEventTouchUpInside];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBnt];

    self.myTableVIew.separatorStyle = UITableViewCellStyleDefault;

    self.myTableVIew.backgroundColor = [UIColor whiteColor];
    
    
    self.myTableVIew.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 100)];
    
    UIView * footerView = self.myTableVIew.tableFooterView;
    
    UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(64, 10, 69, 29)];
    
    [button setImage:[UIImage imageNamed:@"Icon_addSteps"] forState:UIControlStateNormal];
    
    [button addTarget:self action:@selector(addStepsAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * button2 = [[UIButton alloc]initWithFrame:CGRectMake(161, 10, 69, 29)];
    
    [button2 setImage:[UIImage imageNamed:@"Icon_ AdjustSteps"] forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(adjustStepsAction) forControlEvents:UIControlEventTouchUpInside];
    
    [footerView addSubview:button];
    
    [footerView addSubview:button2];
    
    UIButton * releaseBnt = [[UIButton alloc]initWithFrame:CGRectMake(10, 60, 300, 40)];
    
    releaseBnt.layer.cornerRadius = 4;
    releaseBnt.layer.masksToBounds = YES;
    
    releaseBnt.backgroundColor = [UIColor colorWithRed:248/255.0f green:102/255.0f blue:79/255.0f alpha:1.0f];
    
    [releaseBnt setTitle:@"立即发布" forState:UIControlStateNormal];
    
    releaseBnt.titleLabel.font = [UIFont systemFontOfSize:16];
    
    [releaseBnt addTarget:self action:@selector(releaseAction) forControlEvents:UIControlEventTouchUpInside];
    
    [footerView addSubview:releaseBnt];

}
//立即发布
-(void)releaseAction{
    
    if (_writeName.text==nil) {
        self.message = @"菜谱名不能为空";
    }else if (_tipsLabel.text==nil){
        self.message = @"心得不能为空";
    }else if(_promptLabel.text==nil){
        self.message = @"小贴士不能为空";
    }else if (_array.count<3){
        self.message = @"步骤不能少于3步";
    }else{
        self.message = @"是否发布";
    }
    
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:_message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    
    
    [alertView show];
    
    

}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (_writeName.text==nil) {

    }else if (_tipsLabel.text==nil){

    }else if(_promptLabel.text==nil){

    }else if (self.headImage.image==nil){
        
    }else if (_array.count<3){

    }else{
        if (buttonIndex==1) {
            
            NSDictionary * Content = @{@"CookingImageData":_headImage.image,
                                       @"RecipeImageData":_headImage.image,
                                       @"RecipeName": _writeName.text,
                                       @"RecipeShow": _tipsLabel.text,
                                       @"CookingDifficulty": @"一般",
                                       @"CookingTime": @"45分钟",
                                       @"Collection": @"0",
                                       @"CollectionTaste": @"鲜",
                                       @"VideoLink": @"/Users/wenzhaoxu/ForengnMenu/ForengnMenu/西班牙海鲜饭 28_高清.mp4",
                                       @"Praise": @"0"};
            
            NSMutableArray * bufaArrays = [NSMutableArray new];
            
            for (WriteModel * model in _array) {
                static int i = 0;
                i++;
                NSString * number = [NSString stringWithFormat:@"%d",i];
                
                if (model.content != nil && model.image != nil) {
                    model.content = model.content? model.content:@"";
                    model.image = model.image? model.image:[UIImage new];
    
                    NSDictionary *dic = @{@"imageData":model.image,
                                          @"StepsLabel":model.content,
                                          @"NuberLabel":number};
                    
                    [bufaArrays addObject:dic];
                    
                }
                
            }
            
            NSDictionary * dic1 = @{@"foodImage":@"Icon_NeiRong1",@"foofName":@"隔夜米饭",@"foodDosage":@"一碗"};
            NSDictionary * dic2 = @{@"foodImage":@"Icon_NeiRong2",@"foofName":@"鱼露",@"foodDosage":@"10ml"};
            NSDictionary * dic3 = @{@"foodImage":@"Icon_NeiRong3",@"foofName":@"蚝油",@"foodDosage":@"5ml"};
            NSDictionary * dic4 = @{@"foodImage":@"Icon_NeiRong4",@"foofName":@"肉类（自选）",@"foodDosage":@"适量"};
            NSDictionary * dic5 = @{@"foodImage":@"Icon_NeiRong5",@"foofName":@"泰国小辣椒",@"foodDosage":@"一个"};
            NSDictionary * dic6 = @{@"foodImage":@"Icon_NeiRong6",@"foofName":@"彩椒",@"foodDosage":@"1-2个"};
            NSDictionary * dic7 = @{@"foodImage":@"Icon_NeiRong7",@"foofName":@"柠檬",@"foodDosage":@"1-4个"};
            NSDictionary * dic8 = @{@"foodImage":@"Icon_NeiRong8",@"foofName":@"洋葱",@"foodDosage":@"1瓣"};
            
            NSArray * Food = @[dic1,dic2,dic3,dic4,dic5,dic6,dic7,dic8];
        
            NSDictionary * chuan = @{@"Content":Content,
                                 @"Steps":bufaArrays,
                                 @"Food":Food,
                                 @"Tips":_tipsLabel.text,
                                 @"ServiceTips":_promptLabel.text};
            
            UIStoryboard * stroyboard = [UIStoryboard storyboardWithName:@"MyMenu" bundle:[NSBundle mainBundle]];
            
            MyMenuViewController * viewController = [stroyboard instantiateViewControllerWithIdentifier:@"MyMenuController"];
            viewController.isOk = YES;
            viewController.chuan = chuan;
            
            [self.navigationController pushViewController:viewController animated:YES];
        }
    }
    
}
//存草稿
-(void)saveDraft{
    
    UIView * sendView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
    
    sendView.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:sendView];
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 120, 30)];
    
    view.center =CGPointMake(160, 284);
    
    view.backgroundColor = [UIColor blackColor];

    view.layer.cornerRadius = 2;
    view.layer.masksToBounds = YES;
    
    view.alpha = 0;
    
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 120, 30)];
    
    label.center = CGPointMake(160, 284);
    
    label.textAlignment = NSTextAlignmentCenter;
    
    if (_writeName.text==nil) {
        label.text = @"菜谱名不能为空";
    }else if (_tipsLabel.text==nil){
        label.text = @"心得不能为空";
    }else{
        label.text = @"已储存";
    }
    
    label.textColor = [UIColor whiteColor];
    
    label.font = [UIFont systemFontOfSize:14];
    
    [UIView animateWithDuration:1.0 animations:^{
        
        view.alpha = 0.5;
        
        [sendView addSubview:view];
        
        [sendView addSubview:label];
        
    } completion:^(BOOL finished) {
        
        view.alpha = 0;
        
        [view removeFromSuperview];
        
        [sendView removeFromSuperview];
        
        [label removeFromSuperview];
    }];
    
}
-(void)viewWillAppear:(BOOL)animated{

    [self.myTableVIew reloadData];
}
//返回节
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5 + _array.count;
}
//返回行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
//渲染行
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section==0) {
        self.identifier = @"Cell1";
        menuNameTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:_identifier];
        
        UIView * view = (UIView *)[cell viewWithTag:30];
        view.hidden = YES;
        
        if (!self.writeName.text.length==0) {
            cell.addBnt.hidden = YES;
            cell.addNameLabel.hidden = NO;
            cell.addNameLabel.text = self.writeName.text;
        }
        
        return cell;
    }else if (indexPath.section==1) {
        self.identifier = @"Cell1";
        menuNameTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:_identifier];
        UILabel * lable =(UILabel *)[cell viewWithTag:10];
        lable.text = @"心得";
        UIView * view = (UIView *)[cell viewWithTag:30];
        view.hidden = YES;
        
        if (!self.tipsLabel.text.length==0) {
            cell.addBnt.hidden = YES;
            cell.addNameLabel.hidden = NO;
            cell.addNameLabel.text = self.tipsLabel.text;
        }
        
        return cell;
    }else if(indexPath.section==2){
        self.identifier = @"Cell1";
        menuNameTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:_identifier];
        
        UILabel * lable =(UILabel *)[cell viewWithTag:10];
        lable.text = @"食材(至少2项)";
        
        return cell;
    }else if(indexPath.section==3){
        self.identifier = @"Cell1";
        menuNameTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:_identifier];
        
        UILabel * lable =(UILabel *)[cell viewWithTag:10];
        lable.text = @"辅料";
        
        return cell;
    }else if(indexPath.section==4){
        self.identifier = @"Cell1";
        menuNameTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:_identifier];
        if (self.promptLabel.text) {
            cell.addBnt.hidden = YES;
            cell.addNameLabel.hidden = NO;
            cell.addNameLabel.text = self.promptLabel.text;
        }

        UIView * view = (UIView *)[cell viewWithTag:30];
        view.hidden = YES;
        UILabel * lable =(UILabel *)[cell viewWithTag:10];
        lable.text = @"添加";
        
        return cell;
    }else{
        self.identifier = @"Cell2";
        stepsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:_identifier];
        
        
        NSString * string = [NSString stringWithFormat:@"%ld",indexPath.section-4];
        
        cell.stepsLabel.text = string;
        
        WriteModel * model = self.array[indexPath.section-5];
        
        if (model.content) {
            cell.addStepsBnt.hidden = YES;
            cell.addStepsLabel.hidden = NO;
            cell.addStepsLabel.text = model.content;
            
            cell.stepsImageView.image = model.image? model.image:[UIImage imageNamed:@"Icon_ picturess"];
        }else{
            cell.addStepsBnt.hidden = NO;
            cell.addStepsLabel.hidden = YES;
        }
        
        cell.delegate = self;
        
        return cell;
    }
}
//节头
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section==0) {
        UIView * view = [UIView new];
        view.frame = CGRectMake(0, 0, 320, 144);
        
        UIImageView * imageView = [UIImageView new];
        imageView.frame = view.bounds;
        
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        
        if (self.headImage.image) {
            imageView.image = self.headImage.image;
            
        }else{
            imageView.image = [UIImage imageNamed:@"Icon_rendering"];
        }
        
        [view addSubview:imageView];
        
        [tableView addSubview:view];
        
        //轻敲手势
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addVideo)];
        
        //设置手指数量
        tap.numberOfTouchesRequired = 1;
        
        //设置触摸次数
        tap.numberOfTapsRequired = 1;
        
        //添加到ImageView上去
        [view addGestureRecognizer:tap];

        return @"菜谱名(必备)";
    }else if (section==1){
        return @"心得";
    }else if(section==2){
        return @"食材(至少2项)";
    }else if(section==3){
        return @"辅料";
    }else if (section==4){
        return @"小贴士";
    }else if (section==5){
        return @"做法步骤(至少3步)";
    }else{
        return nil;
    }

}

//节尾
- (nullable NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{

    return nil;
}
//节头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section==0) {
        return 143 + 34;
    }else if (section==1) {
        return 12;
    }else if (section==2) {
        return 12;
    }else if (section==3) {
        return 12;
    }else if(section==4){
        return 12;
    }else if(section==5){
        return 12;
    }else{
        return 1;
    }
}
//结尾高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    if (section==0) {
        return 15;
    }else if (section==1) {
        return 15;
    }else if (section==2) {
        return 15;
    }else if (section==3) {
        return 15;
    }else if (section==4) {
        return 15;
    }else if(section==5){
        return 20;
    }else{
        return 1;
    }
}
//Cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section==0) {
        return 40;
    }if (indexPath.section==1) {
        return 40;
    }if (indexPath.section==2) {
        return 40;
    }if (indexPath.section==3) {
        return 40;
    }if (indexPath.section==4) {
        return 40;
    }else{
        return 150;
    }

}
//选择状态
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section==0) {
        [self performSegueWithIdentifier:@"name" sender:indexPath];
    }else if (indexPath.section==1){
        [self performSegueWithIdentifier:@"tips" sender:indexPath];
    }else if (indexPath.section==2){
        [self performSegueWithIdentifier:@"ingredients" sender:indexPath];
    }else if (indexPath.section==3){
        [self performSegueWithIdentifier:@"material" sender:indexPath];
    }else if (indexPath.section==4){
        [self performSegueWithIdentifier:@"prompt" sender:indexPath];
    }else{
        [self performSegueWithIdentifier:@"writeSteps" sender:indexPath];
    }

    
}
//返回节头View
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
}
//返回节尾View
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;

}
//传值
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    if ([segue.identifier isEqualToString:@"name"]) {
        writeNameViewController * detail = segue.destinationViewController;
        
        [detail changeWithTitle:self.writeName.text withBlock:^(NSString *content) {
            self.writeName.text = content;
            
        }];
    }else if([segue.identifier isEqualToString:@"tips"]){
        
        writeNameViewController * detail = segue.destinationViewController;
        
        [detail changeWithTitle:self.tipsLabel.text withBlock:^(NSString *content) {
            self.tipsLabel.text = content;
            
        }];

    }else if ([segue.identifier isEqualToString:@"writeSteps"]){
        
        NSIndexPath * indexPath = (NSIndexPath *)sender;
        
        writeStepsViewController * detail = segue.destinationViewController;
        
        [detail changeWithTitle:self.tipsLabel.text withBlock:^(NSString *content) {
            
            if (content) {
                
                WriteModel * model = self.array[indexPath.section-5];
                
                model.content = content;
                
                stepsTableViewCell * cell = [self.myTableVIew cellForRowAtIndexPath:indexPath];
                cell.addStepsLabel.text = content;
                cell.addStepsBnt.hidden = YES;
                cell.addStepsLabel.hidden = NO;
            }
            
        }];
        
    }else if([segue.identifier isEqualToString:@"prompt"]){
        
        writeNameViewController * detail = segue.destinationViewController;
        
        [detail changeWithTitle:self.promptLabel.text withBlock:^(NSString *content) {
            self.promptLabel.text = content;
            
        }];
        
    }
}
//添加步骤
-(void)addStepsAction{
    
    WriteModel * model = [WriteModel new];
   [_array addObject:model];
    
   [self.myTableVIew reloadData];
    
}
//调整步骤
-(void)adjustStepsAction{

}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    if (picker.view.tag == 1) {
        
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        WriteModel * model = self.array[self.selectedImageViewIndexPath.section - 5];
        model.image = image;
        stepsTableViewCell * cell = [self.myTableVIew cellForRowAtIndexPath:self.selectedImageViewIndexPath];
        cell.stepsImageView.image = image;

    }else{
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        self.headImage.image = image;
    }
    
    
}
//添加步骤图
-(void)stepsImageWillAction:(UIImageView *)stepsImageView withCell:(stepsTableViewCell *)cell{
    
    self.selectedImageViewIndexPath = [self.myTableVIew indexPathForCell:cell];
    
        //警告视图
        UIAlertController * alertCtr = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
        UIAlertAction *firstAction = [UIAlertAction actionWithTitle:@"从本地选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    
            // 跳转到相机或相册页面
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.view.tag = 1;
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            
            [self presentViewController:imagePickerController animated:YES completion:^{
                
                
            }];
            
        }];
    
        UIAlertAction *secondAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            
        }];
    
        UIAlertAction *thirdAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        }];
    
    
        [alertCtr addAction:firstAction];
    
        [alertCtr addAction:secondAction];
    
        [alertCtr addAction:thirdAction];
    
        [self presentViewController:alertCtr animated:YES completion:^{}];

}
//添加视频
-(void)addVideo{
    //警告视图
    UIAlertController * alertCtr = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *firstAction = [UIAlertAction actionWithTitle:@"从本地选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.view.tag = 0;
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        
        [self presentViewController:imagePickerController animated:YES completion:^{
            
            
        }];


    }];
    UIAlertAction *secondAction = [UIAlertAction actionWithTitle:@"录制" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
    
    UIAlertAction *thirdAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {}];
    
    [alertCtr addAction:firstAction];
    
    [alertCtr addAction:secondAction];
    
    [alertCtr addAction:thirdAction];
    
    [self presentViewController:alertCtr animated:YES completion:^{}];

}
@end
